//index.js
//获取应用实例
const app = getApp();


Page({
  data: {
    userInfo: {
      avatarUrl: './user-unlogin.png',
    },
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    type : 0
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    if (this.data.hasUserInfo == false){
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true,
            type: 0
          })
        }
      });
    }
  },
  
  onShow: function() {
    this.queryUser();
  },

  getUserInfo: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true,
      type: 0
    })
    this.saveUser();
  },

  saveUser: function() {
    const db = wx.cloud.database({});
    const t_user = db.collection('user');
    t_user.add({
      data: {
        type: 0,
        avatarUrl: app.globalData.userInfo.avatarUrl,
        nickName: app.globalData.userInfo.nickName,
      }
    })
  },

  queryUser: function() {
    console.log("查询用户");
    const db = wx.cloud.database({});
    const t_user = db.collection('user');
    t_user.where({
      _openid: app.globalData.openid
    }).get({
      success: res => {
        console.log(res);
        var user = res.data[0];
        if (user != null){
          this.setData({
            userInfo: user,
            type: user.type,
            hasUserInfo: true
          })
        }
        
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
  }
})
